package com.jp.knowledge.fragment;


import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.activity.SkillDetailActivity;
import com.jp.knowledge.adapter.CommtemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.SearchCommtemAdapter;
import com.jp.knowledge.adapter.SecondLevelCommAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.command.Command;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.dialog.SkillDetailPopuWindow;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.model.SkillModel;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class SkillDetailFragment extends BaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener, View.OnClickListener{


    private static final int REFRESH_CODE = 0x01;
    private static final int LOAD_MORE_CODE = 0x02;

    @ViewInject(R.id.refresh)
    private CanRefreshLayout refreshLayout;
    @ViewInject(R.id.can_content_view)
    private RecyclerView recyclerView;

    private SecondLevelCommAdapter adapter;
    private List<HeadLineData> headLineDatas;
    private int page;

    private List<PositionKnowlegeMode.ListBeanX> data;
    private boolean isPositionTool;
    private int mainPosition;
    private int subPosition;

    private View contentView;

    private int type;

    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast localBroadCast;

    private String cachePath;
    private FileCacheManager cacheManager;

    public SkillDetailFragment() {
    }

    public SkillDetailFragment settype(int type){
        this.type=type;
        return  this;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.fragment_skill_detail, container, false);
        x.view().inject(this,contentView);
        init();
        return contentView;
    }
    protected void init() {
        Intent intent = getActivity().getIntent();
        data = (List<PositionKnowlegeMode.ListBeanX>) intent.getSerializableExtra("data");
        mainPosition = intent.getIntExtra("mainPosition", 0);
        subPosition = intent.getIntExtra("subPosition", 0);
        isPositionTool = intent.getBooleanExtra("isPositionTool", false);
        if(data == null){
            getActivity().finish();
            return;
        }
        page = 1;
        headLineDatas = new ArrayList<>();
        initCache();
        initBroadcast();
        initView();
//        refresh();
        readCache();
    }

    private void initCache(){
        cachePath = mContext.getCacheDir().getPath()+"/skill_detail_data_"
                +data.get(mainPosition).getList().get(subPosition).getId()+".data";
        cacheManager = new FileCacheManager();
    }

    private void saveCache(final List<HeadLineData> data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(data == null)
                    return;
                List<HeadLineData> tmpData = new ArrayList<>();
                if(data.size() <= 20)
                    tmpData.addAll(data);
                else
                    for(int i = 0; i < 20; i++)
                        tmpData.add(data.get(i));
                cacheManager.wirteObject(tmpData, path);
            }
        }).start();
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<HeadLineData>>() {
            @Override
            public void call(Subscriber<? super List<HeadLineData>> subscriber) {
                List<HeadLineData> list = (List<HeadLineData>) cacheManager.readObject(cachePath);
                subscriber.onNext(list);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer< List<HeadLineData>>() {
            @Override
            public void onCompleted() {
                if(adapter.getItemCount() > 0)
                    onRefresh();
                else
                    refreshLayout.autoRefresh();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<HeadLineData> data) {
                headLineDatas.clear();
                if(data != null && data.size() > 0)
                    headLineDatas.addAll(data);
                adapter.updataAdapter(headLineDatas);
            }
        });
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        saveCache(headLineDatas, cachePath);
        super.onDestroy();
    }

    private void initBroadcast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                if(LocalBroadCast.COMM_CHANGE_SIZE.equals(intent.getAction())) {
                    adapter.changeTextSize();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.COMM_CHANGE_SIZE);//改变字体大小
        localBroadcastManager.registerReceiver(localBroadCast,intentFilter);
    }

    public void setValue( int mainPosition, int subPosition){
        this.mainPosition=mainPosition;
        this.subPosition=subPosition;
    }

    /***
     * 刷新
     */
    public void refresh(){
        refreshLayout.autoRefresh();
    }
    private void initView(){
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        headLineDatas = new ArrayList<>();
        adapter = new SecondLevelCommAdapter(mContext, headLineDatas);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {
                adapter.updateTitleColor(position);
//                Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
//                intent.putExtra("id", headLineDatas.get(position).getId());
//                intent.putExtra("type", headLineDatas.get(position).getType());
//                intent.putExtra("linkTitle", headLineDatas.get(position).getTitle());
//                try {
//                    intent.putExtra("linkIcon", headLineDatas.get(position).getImglist().get(0).getSrc());
//                }catch (Exception e){} finally {
//                    startActivity(intent);
//                }
                HeadLineData data = headLineDatas.get(position);
                CommandReceiver commandReceiver = new CommandReceiver.Builder(mContext)
                        .withCompanyId(data.getCompanyId())
                        .withRecordId(data.getRecordId())
                        .withParameterId(data.getType()+"")
                        .build();
                Command commandObject = Command.create(data.getCommand(), commandReceiver);
                CommandInvoker.executeCommand(commandObject);
            }
        });

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
    }

    @Override
    public void onRefresh() {
        getData(true);
    }

    @Override
    public void onLoadMore() {
        getData(false);
    }

    private void getData(boolean isRefresh){
        JsonObject param = new JsonObject();
        if(isRefresh) {
            page = 1;
            param.addProperty("page", page);
        } else{
            param.addProperty("page", ++page);
        }
        param.addProperty("type", type);
        if(isPositionTool) {          // 岗位工具
            param.addProperty("id", data.get(mainPosition).getList().get(subPosition).getId());
            HttpHelper.getInstance(mContext).toolList(param,
                    isRefresh ? REFRESH_CODE : LOAD_MORE_CODE, this);
        } else {                        // 岗位知识
            param.addProperty("navTypeId", data.get(mainPosition).getList().get(subPosition).getId());
            HttpHelper.getInstance(mContext).skillDetail(param,
                    isRefresh ? REFRESH_CODE : LOAD_MORE_CODE, this);
        }
    }

    @Override
    public void onClick(View v) {
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_CODE){
            refreshLayout.refreshComplete();
        } else if(requestType == LOAD_MORE_CODE){
            refreshLayout.loadMoreComplete();
        }
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == REFRESH_CODE || requestType == LOAD_MORE_CODE){
            List<HeadLineData> datas = data.getList(HeadLineData.class);
            if(requestType == REFRESH_CODE)
                headLineDatas.clear();
            if(datas != null && datas.size() > 0)
                headLineDatas.addAll(datas);
            adapter.updataAdapter(headLineDatas);
        }
    }
}
